﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Net.Mail;
using LootPoints.Security;

namespace LootPoints.Pages
{
    public partial class PasswordReset : Page
    {
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            try { if ((bool)Session["logged"] == true) Response.Redirect("~/Pages/Overview.aspx"); }
            catch { /* User isnt logged in, stay on page */ }
        }

        protected void btnBack_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Login.aspx");
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                ModelContainer context = new ModelContainer();
                Character character = (from c in context.Character where c.Name == tbUsername.Text select c).FirstOrDefault();
                if (character != null)
                {
                    if (character.Email != tbEmail.Text) lblEmail.Text = " Does not match...";
                    else
                    {
                        character.Reset = true;
                        string resetCode = character.Name + new Random().Next(10000, 99999).ToString();
                        character.ResetCode = Hashing.CreateHash(resetCode);
                        context.SaveChanges();
                        if (Mail.SendResetMail(character, resetCode)) mpeAdd.Show();
                        else lblUsername.Text = "Email not sent";
                    }
                }
                else lblUsername.Text = " Does not exist...";
            }
        }

        protected void btnOK_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Pages/Login.aspx");
        }
    }

    public static partial class Mail
    {
        public static bool SendResetMail(Character character, string resetCode)
        {
            try
            {
                MailMessage mail = new MailMessage();
                SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

                mail.From = new MailAddress("nickvroomen@gmail.com");
                mail.To.Add(character.Email);
                mail.Subject = "ESi lootpoints password reset";
                mail.Body = "Please click:<br /><a href='http://h1930546.stratoserver.net/esiloot/Pages/ResetTool.aspx?code=" + resetCode + "'>This link</a><br />To reset your password.";

                SmtpServer.Port = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("nickvroomen@gmail.com", "0701nick");
                SmtpServer.EnableSsl = true;

                SmtpServer.Send(mail);
                return true;
            }
            catch { return false; }
        }
    }
}